
/* txt2bin (C) Copyright Bill Buckels 2008 */
/* Visual Studio 2005 Console Application */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys\stat.h>
#include <string.h>



char buffer[256], outbuf[256], outfile[256];


int main(int argc, char **argv)
{
	int fh, idx, jdx, len;
	FILE *fp;

    /* args */
	if (argc != 3) {
	    printf("Usage is \"nTxt2Bin infile recordlength\"\n");

	}
	else {
		len = atoi(argv[2]);
		/* len */
		if (len < 1 || len > 255) {
			printf("Recordlength must be between 1-255\n");
		}
		else {
			fp = fopen(argv[1], "r");
			/* fp */
			if (NULL == fp) {
			  printf("Can't open %s\n", argv[1]);
			}
			else {
				strcpy(outfile, argv[1]);
				jdx = 999;
				for (idx = 0; outfile[idx] != 0; idx++) {
					if (outfile[idx] == '.')jdx=idx;
				}
				if (jdx != 999) outfile[jdx] = 0;
				strcat(outfile,".BIN");

				fh = _open(outfile, O_CREAT | O_TRUNC | O_WRONLY | O_BINARY, S_IWRITE);
                /* fh */
				if (fh == -1 ) {
					printf("Can't open %s\n", outfile);
				}
				else {
					while (NULL != fgets(buffer, 256, fp)) {
						for (idx = 0; idx < len; idx++)outbuf[idx] = 0;
						for (idx = 0; buffer[idx] != 0; idx++) {
						   if (buffer[idx] == 13 || buffer[idx] == 10)buffer[idx] = 0;

						}
						strcpy(outbuf, buffer);
						_write(fh, outbuf, len);
					}
					_close(fh);
					printf("%s created!\n",outfile);
				}
				/* fh */

				fclose(fp);
			}
			/* fp */
		}
		/* len */
   }
   /* args */
	return 0;
}